﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using T.FAS.Runtime.Metadata.Entity.DataModel;
using T.FAS.Runtime.Metadata.Entity;

namespace T.FAS.Runtime.Metadata.Entity.DataModel
{
    [Serializable]
    public class CompositeDataObjectRefSchemaEntity : IRefSchemaEntity
    {
        public string ID { get; set; }
        public string Code { get; set; }
        public string Name { get; set; }
        public Dictionary<string, Node> Nodes { get; set; }

        [Serializable]
        public class Node
        {
            public string Code { get; set; }
            public Dictionary<string, Element> Elements { get; set; }
            public Dictionary<string, Node> Nodes { get; set; }

            public static Node Mapping(CompositeDataObject cdo, CompositeNodeObject cno)
            {
                if (cdo == null || cno == null) return default;
                var node = new Node
                {
                    Code = cno.DataObjectTableAlias,
                    Elements = new Dictionary<string, Element>()
                };
                var refEles = cno.Elements.Where(e => e.ElementType == ElementType.Reference);
                if (refEles != null) {
                    foreach (var ele in refEles)
                    {
                        node.Elements[(ele.Alias ?? ele.Name)] = Element.Mapping(cdo, cno, ele);
                    }
                }
                return node;
            }
        }

        [Serializable]
        public class Element
        {
            public string Code { get; set; }
            public string Text { get; set; }
            public string DataType { get; set; }
            public ElementType ElementType { get; set; }
            public int Length { get; set; }
            public int Precision { get; set; }
            public bool IsAllowNull { get; set; }

            public static Element Mapping(CompositeDataObject cdo, CompositeNodeObject cno, CompositeNodeObjectElement ele)
            {
                if (cdo == null || cno == null || ele == null) return default;
                var el = new Element
                {
                    Code = ele.Alias ?? ele.Name,
                    Text = ele.DisplayName,
                    DataType = ele.DataType.ToString(),
                    Length = ele.Length,
                    Precision = ele.Precision,
                    ElementType = ele.ElementType,
                    IsAllowNull = ele.IsAllowNull,
                };
                return el;
            }
        }
    }
}
